<template>
  <view class="content">
    <van-nav-bar :title="scrolling ? navBarTitle : ''" left-arrow @click-left="onClickLeft" v-if="pageSign==='mine'" id="navBar"> </van-nav-bar>
    <van-nav-bar :title="navBarTitle" left-arrow @click-left="onClickLeft" v-else id="navBar"> </van-nav-bar>


    <!-- <loading :loadingIsShow="loadingIsShow"></loading> -->
    <view class="main-container">
      <view class="topBox" v-if="pageSign !=='mine'">
        <view class="sort-menu">
          <view class="sort_option item_option"
            :class="{'sort_option_selected': current===index}"
            v-for="(item, index) in sortList" :key="index" :id="item.id" @click="changeSort(index, $event, item)">
            {{ item.filterName }} <van-icon name="arrow-down"  style="margin-left: 12rpx;"/>
            <!-- <view class="sort_option"  :class="{'sort_option_selected': current===index}" @click="changeSort(index, $event, item)"></view> -->
          </view>
         
        </view>
      </view>
      <scroll-view :refresher-enabled="false" class="scroll-content" @scroll="scrollPage" scroll-y :lower-threshold="80" @scrolltolower="loadMore"
        show-scrollbar="false" >
        <view class="scroll-box">
          <view class="list_title" v-if="pageSign==='mine'">{{ navBarTitle }}</view>
          <view class="activity_content  ">
            <view class="box_content" v-for="(i, j) in actContent" :key="j" @click="toActivityDetail(i)">
                <view class="content_img"><img :src="i.image" alt="" mode="widthFix"> <view class="status_tips" v-if="pageSign!=='mine'" :class="{'end_status_tips':i.activities.status == 3}">{{i.statusText}} </view> </view>
                <template  v-if="pageSign!=='mine'">
                  <view class="content_text act_text">
                    <view class="content_text_title act_title">{{ i.activities.title }}</view>
                    <view class="content_text_subtitle " > 
                      <view style="line-height:26rpx"><img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/clock.png" alt="" style="width: 26rpx; height: 26rpx;margin-right: 14rpx;" > </view>
                      <view class="content_text_startTime"> {{ i.monthAndDay }} {{i.weekDay}}  {{ i.times}}</view>
                    </view>
                    <view class="content_text_address">
                      <view style="line-height:26rpx"><img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/position.png" style="width: 22rpx; height: 26rpx;margin-right: 14rpx;" /> </view>
                      <view class="content_text_location">{{ i.activities.addressDetail }}</view> 
                    </view>
                  </view>
                </template>
                <template v-if="pageSign==='mine'">
                    <view class="content_text act_text" >
                    <view class="content_text_subtitle " > 
                      <view class="content_text_startTime"> {{ i.startTime }}{{i.weekDay}}</view>
                    </view>
                    <view class="content_text_title act_title">{{ i.title }}</view>             
                    <view class="content_text_actStatus"> {{i.statusText}} </view>
                  </view>
                </template>
            </view>
          </view>
          <view v-if="loading" class="loading-text">正在加载...</view>
          <view v-if="finished" class="no-more-text">没有更多了</view>
        </view>
      </scroll-view>
    </view>
    <signupRestrictionPopup :show="showSignupRestriction" :signupRestriction="signupRestriction" @closeRestrictionPopup=closeRestrictionPopup></signupRestrictionPopup>
    <calendar :show="showCalendar" @onCloseCalendar="onCloseCalendar" @onConfirmCalendar="onConfirmCalendar" :sign="'activity'"></calendar>
    <selectArea :show="selectorVisible"  :level="2" @closePopup = "closeRestrictionPopup" @finish="finishSelectArea"></selectArea>
    <!-- <van-calendar :show="showCalendar" title="日期选择" show-subtitle="true" show-title="true" color="#ff6203" type="range" @close="onCloseCalendar" @confirm="onConfirmCalendar" /> -->
  </view>
</template>

<script>
import { topStyleWhite, topStyleBlack } from '@/utils/topColor'
import { getActivityListApi,getMyActivitiesApi ,getPropertyActivityListApi} from '@/api/activity'
import signupRestrictionPopup from '@/mycomponents/activity/signupRestrictionPopup.vue'
import calendar from '@/mycomponents/activity/calendar.vue'
import  { PAGE_TYPE } from '@/utils/constant'
import selectArea from '@/mycomponents/addressModele/selectArea.vue'

export default {
  components: {
    signupRestrictionPopup,
    calendar,
    selectArea
  },
  data() {
    return {

      navBarTitle: '我的活动',
      scrolling: false, // 顶部区域吸顶效果
      current:0, //页面顶部的筛选条件
      sortList:[
        {
          filterNum:'0',
          filterName:'时间'
        },
        {
          filterNum:'1',
          filterName:'运城市'
        },
        {
          filterNum:'2',
          filterName:'报名活动限制'
        },
      ],
      showSignupRestriction:false, // 报名限制弹窗
      showCalendar:false, // 日历弹窗
      actContent: [
        // {
        //   image: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/actImg1.png',
        //   title: "社区活动 | 零基础瑜伽体验活动",
        //   startTime: '10月13日 周六 14:00-16:00',
        //   addressDetail: "水岸华庭·东郡 | 篮球场",
        //   status: 0
        // },
        // {
        //   // imgurl: require("../../static/actImg2.png"),
        //   image: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/actImg1.png',
        //   title: "公益活动|心肺复苏 CPR+AED 培训活动",
        //   startTime: '10月20日 19:00-21:00',
        //   addressDetail: "盐湖区 | 金鑫大酒店",
        //   status: 0 // 0未发布    1报名中    2报名已满  3已结束    4已取消
        // },
        // {
        //   // imgurl: require("../../static/actImg2.png"),
        //   image: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/actImg1.png',
        //   title: "公益活动|心肺复苏 CPR+AED 培训活动",
        //   startTime: '10月20日 19:00-21:00',
        //   addressDetail: "盐湖区 | 金鑫大酒店",
        //   status: 1
        // },
        // {
        //   // imgurl: require("../../static/actImg2.png"),
        //   image: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/actImg1.png',
        //   title: "公益活动|心肺复苏 CPR+AED 培训活动",
        //   startTime: '10月20日 19:00-21:00',
        //   addressDetail: "盐湖区 | 金鑫大酒店",
        //   status: 2
        // }
    ],
      pageSign: 'find', // 活动列表的筛选条件  我的活动  发现首页
      params: {}, // 路由携带的参数
      startDate: undefined, // 开始时间
      endDate: undefined, // 结束时间
      province: '山西省', // 省
      city: '运城市', // 市
      county: undefined, // 区
      signupRestriction: 0, // 报名限制  0 全员可报 1 仅限业主  2 制定小区
      communityId: undefined, // 小区id
      pageNum: 1,
      pageSize: 10,
      total: 0,
      isLoadAll: false,
      uid:undefined,
      fromEarnPoints: false,
      loading: false,
      finished: false,
      pageType: undefined, // 页面类型
      selectorVisible: false,

    }
  },
  onLoad(data) {
    // 取到路由携带的参数
    if (data && data.params) {
      this.params = JSON.parse(decodeURIComponent(data.params || '{}'))
      console.log('params', this.params)
      this.pageType = this.params.pageType || PAGE_TYPE.FIND
      if(this.pageType == PAGE_TYPE.MINE  ){
        this.pageSign = 'mine'
        this.navBarTitle='我的活动'
      }else{
        this.pageSign ='find'
        this.navBarTitle='活动'
      }
      this.fromEarnPoints = this.params.fromEarnPoints || false
    }
  },
  onReady() {
    topStyleWhite()
   
  },
  onShow(){
    if(this.province && this.city && this.county){
      this.sortList[1].filterName = this.county
    }else if(this.province && this.city && !this.county){
      this.sortList[1].filterName = this.city
    }else if(this.province && !this.city && !this.county){
      this.sortList[1].filterName = this.province
    }else{
      this.sortList[1].filterName = '运城市'
    }
    // if(this.pageSign==='mine'){
    //   this.getMyActivityList()   //我的活动
    // }else{
    //   this.getActivityList()   //发现首页--活动列表
    // }
      if (this.pageType == PAGE_TYPE.MINE){
         this.getMyActivityList()   //我的活动
      } else if (this.pageType == PAGE_TYPE.FIND) {
         this.getActivityList()   //发现首页--活动列表
      } else if (this.pageType == PAGE_TYPE.COMMUNITY) {
        this.getCommunityActivityList()   //社区首页--活动列表
      } 
  },
  methods: {
    // 互动页面
    scrollPage(e) {
      console.log(e.detail.scrollTop, this.scrolling)
      if (e.detail.scrollTop > 25 && !this.scrolling) {
        this.scrolling = true
      } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
        this.scrolling = false
      }
    },

    onClickLeft() {
      if (this.pageType == PAGE_TYPE.MINE){
        uni.switchTab({ url: '/pages/my/mine' })
      } else if (this.pageType == PAGE_TYPE.FIND) {
        uni.switchTab({ url: '/pages/find/index' })
      } else if (this.pageType == PAGE_TYPE.COMMUNITY) {
        uni.switchTab({ url: '/pages/community/index' })
      } else{
        uni.navigateBack()
      }
    },
    loadMore() {
      if (!this.finished) {
        this.getActivityList();
      }
    },
    // 格式化时间  取出startTime中的时间部分
    formatTime(timeString) {
      if (!timeString) return '';
      return timeString.split(' ')[1]; // 分割字符串取时间部分
    },
    formatDate(date) {
      date = new Date(date);
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    formatFullDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0') // 月份补零
        const day = String(date.getDate()).padStart(2, '0')      // 日期补零
        return `${year}-${month}-${day}`
    },
    // 活动状态修改
    formatStatus(status) {
        const mineStatusMap = {
            0: '已报名',
            1: '已参加',
            2: '已取消'
        };
        
        const normalStatusMap = {
            0: '未发布',
            1: '报名中',
            2: '报名已满',
            3: '已结束',
            4: '已取消'
        };
        return this.pageSign == 'mine' 
            ? mineStatusMap[status] || ''
            : normalStatusMap[status] || '';
    },
    // 页面顶部的tab
    changeSort(index,e,item){
      this.current = index
      this.handleSelected(index)
    },
    handleSelected(index){
      switch(index) {
        case 0:
          this.showCalendar = true
          break
        case 1:
          this.selectorVisible = true
          break
        case 2:
          this.showSignupRestriction = true
          break
      }
    },

        // 活动限制  关闭弹窗
        closeRestrictionPopup(){
          this.showSignupRestriction=false
          this.showCalendar = false;
          this.selectorVisible = false
        },
        // 选择活动的限制
        next(type){
          console.log(type)
          this.signupRestriction = type
        },

        // 日历
        // 关闭日历
        onCloseCalendar() {
          this.showCalendar = false;
        },
        // 确认日历
        onConfirmCalendar(detail) {
            console.log(detail)
            const startDateStr = this.formatFullDate(detail[0])
            const endDateStr = this.formatFullDate(detail[1])
            console.log('日期范围:', startDateStr, '至', endDateStr)
            this.startDate = startDateStr
            this.endDate = endDateStr
            this.pageNum = 1
            this.loading = false
            this.finished = false
            this.actContent = []
            this.getActivityList()
            this.showCalendar = false;
        },

        // 选择地区
        finishSelectArea(fieldValue, value) {
            console.log(fieldValue, value)
            const e = fieldValue.split('/')
            console.log(e,'e')
            this.province = e[0]
            this.city = e[1]
            this.sortList[1].filterName = e[1]
            // this.county = e.county
            this.pageNum = 1
            this.loading = false
            this.finished = false
            this.actContent = []
            this.getActivityList()
        },

        // 跳转活动详情
        toActivityDetail(i){
          const params ={
            pageType:this.pageType,
            pageSign:this.pageSign,
            activitiesId:this.pageType !== PAGE_TYPE.MINE? i.activities.id : i.activitieId,  //活动id
            signUpActId:this.pageType !== PAGE_TYPE.MINE? undefined : i.activitySignupId,  //活动报名id
            activityStatus:this.pageType !== PAGE_TYPE.MINE? i.status : i.activitySignupStatus,
            fromEarnPoints: this.fromEarnPoints,
            isSignedUp:this.pageType !== PAGE_TYPE.MINE? i.isSignedUp : i.activitySignupStatus,
          }
          this.changePage(this.pageSign,this.pageType,i,params)
        
        },

        
        changePage( pageSymbol,pageType,item,params ) {
          if(pageSymbol === 'mine' || pageType == PAGE_TYPE.MINE){
            uni.navigateTo({
              url:'/pages/findPage/registResult?params=' +
                    encodeURIComponent(JSON.stringify(params))
                })
          }else{
              uni.navigateTo({
              url:'/pages/findPage/activityDetail?params=' +
                    encodeURIComponent(JSON.stringify(params))
                })
          }
        },

        // 活动列表
        getActivityList() {
          if (this.loading || this.finished) return;
          this.loading = true;

          const apiParams = {
            ...(this.startDate && {startTime: this.startDate}),
            ...(this.endDate && {endTime: this.endDate}),
            // startTime: this.startDate,
            // endTime: this.endDate,
            province: this.province,
            // city: this.city,
            ...(this.city && {city: this.city}),
            signupRestriction: this.signupRestriction, //活动报名限制
            // communityId: this.communityId, //社区id
            pageNum: this.pageNum,
            pageSize: this.pageSize,
          }
          console.log(apiParams,'apiParams')
          return new Promise((resolve, reject) => {
            getActivityListApi(apiParams ).then((res) => {
              console.log(res.data)
              if (res.code === 200) {
                this.total = res.data.total;
                // 修改数据合并方式
                this.actContent = this.pageNum === 1
                  ? res.data.list
                  : [...this.actContent, ...res.data.list];

                this.actContent.forEach(item => {
                  item.image = 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/actImg1.png'
                  item.statusText = this.formatStatus(item.activities.status)
                  item.times = this.formatTime(item.activities.startTime)
                })
                this.finished = this.actContent.length >= this.total;
                this.pageNum++;
                console.log(this.actContent, 'this.orderList')
                this.isOrder = this.actContent.length > 0

                resolve(res)
              } else {
                reject(res)
              }
            }).finally(() => {
              this.loading = false;
            })
          })
        },
        // 我的活动列表
        getMyActivityList() {
          if (this.loading || this.finished) return;
          this.loading = true;

          // const apiParams = {
          //   startTime: this.startDate,
          //   endTime: this.endDate,
          //   province: this.province,
          //   city: this.city,
          //   signupRestriction: this.signupRestriction, //活动报名限制
          //   communityId: this.communityId, //社区id
          //   pageNum: this.pageNum,
          //   pageSize: this.pageSize,
          // }
          return new Promise((resolve, reject) => {
            getMyActivitiesApi({  }).then((res) => {
              console.log(res.data)
              if (res.code === 200) {
                this.actContent = res.data;
                // this.total = res.data.total;
                // // 修改数据合并方式
                // this.actContent = this.pageNum === 1
                //   ? res.data.list
                //   : [...this.actContent, ...res.data.list];

                this.actContent.forEach(item => {
                  item.image = 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/actImg1.png',
                  item.statusText = this.formatStatus(item.activitySignupStatus)
                })
                // this.finished = this.actContent.length >= this.total;
                // this.pageNum++;
                // console.log(this.actContent, 'this.orderList')
                // this.isOrder = this.actContent.length > 0

                resolve(res)
              } else {
                reject(res)
              }
            }).finally(() => {
              this.loading = false;
            })
          })
        },

    		// 活动列表
        getCommunityActivityList() {
          if (this.loading || this.finished) return;
          this.loading = true;

          const apiParams = {
            ...(this.startDate && { startTime: this.startDate }),
            ...(this.endDate && { endTime: this.endDate }),
            province: this.province,
            city: this.city,
            signupRestriction: this.signupRestriction, //活动报名限制
            ...(this.communityId && {communityId: this.communityId}), // 小区id
            pageNum: this.pageNum,
            pageSize: this.pageSize,
          }
          console.log(apiParams,'apiParams')
          return new Promise((resolve, reject) => {
            getPropertyActivityListApi(apiParams).then((res) => {
              console.log(res.data)
              if (res.code === 200) {
                this.total = res.data.total;
                // 修改数据合并方式
                this.actList = this.pageNum === 1
                ? res.data.list
                : [...this.actList, ...res.data.list];

                this.actList.forEach(item => {
                item.image = 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/actImg1.png'
                item.statusText = this.formatStatus(item.activities.status)
                item.times = this.formatTime(item.activities.startTime)
                })
                this.finished = this.actList.length >= this.total;
                this.pageNum++;
                console.log(this.actList, 'this.orderList')
                this.isOrder = this.actList.length > 0

                resolve(res)
              } else {
                reject(res)
              }
              }).finally(() => {
              this.loading = false;
              })
          })
        },
  }
}
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  height: 100vh;
  overflow: hidden;
  z-index: -2;
  background: #ffffff;
  background-size: 100%;

}

.main-container {
  background: #ffffff;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
}


.topBox {
  margin-top: 10px;

  // 全部分类  menu
  .sort-menu {
    display: flex;
    margin-bottom: 18rpx;
    align-items: center;
    padding-left: 24px;
    padding-right: 24px;
    background: #f9f9f9;
    height: 70rpx;
    line-height: 70rpx;

    .sort_option {
      display: flex;
      align-items: center;
      // flex: auto;
      margin-right: 36rpx;
      font-size: 26rpx;
      line-height: 26rpx;
      text-align: left;
      color: #888888
    }
    .item_option{
      color: #888888
    }

    .sort_option_selected {
      font-size: 26rpx;
      line-height: 26rpx;
      text-align: left;
      color: #111111;
    }
  }

}

// 滚动
.scroll-content {
  flex: 1;
  height: 1px;
}

.scroll-box {
  padding-left: 24px;
  padding-right: 24px;
  height: 100vh;
  // background: white;
  // background: palevioletred;
}

.list_title {
  // font-size: 20px;
  font-size: 60rpx;
  margin-bottom:70rpx;
}

// 社区商家活动部分 盒子样式
.box_content {
    display: flex;
		border-radius: 6rpx;
		background: #ffffff;
		// padding: 24rpx 20rpx 24rpx 24rpx;
		margin-bottom: 40rpx;

	.content_img {
    position: relative;
		margin-right: 20rpx;
		width: 20%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		img{
			// width: 112rpx;
			// height: 112rpx;
			width: 100%;
			height: auto;
		}
	}

// 图片上的标识
  .status_tips {
    position: absolute;
    height: 34rpx;
    // width: 50%;
    background: #FF6203;
    border-radius: 0rpx 50rpx 50rpx 0rpx;
    align-items: center;
    text-align: center;
    line-height: 34rpx;
    font-size: 20rpx;
    text-align: center;
    color: #ffffff;
    bottom: 19rpx;
    padding: 0rpx 10rpx;
}
.end_status_tips{
  background-color: rgba(239,239,239,1);
  color: rgba(154,154,154,1);
}

	.content_text {
		width: calc(80% - 20rpx);
		display: flex;
		justify-content: space-between;
		flex-direction: column;

		.content_text_title {
			color: #111111;
			font-size: 26rpx;
			text-align: left;
			line-height: 36rpx;
			max-width: 100%;
		}


		// 超过一行省略
		.act_title{
			max-width: 100%;
      // 超过两行  文字用省略号
      display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: normal;
		}



		.content_text_subtitle {
      display: flex;
      align-items: center;
			max-width: 100%;
      white-space: nowrap;
      /* 防止文本换行 */
      overflow: hidden;
      /* 超出部分隐藏 */
      text-overflow: ellipsis;
      /* 显示省略号 */
      .content_text_startTime{
        // line-height: 24rpx;
        // height: 24rpx;
        font-size: 24rpx;
        text-align: left;
        color: #666666;
      }
		}

		// 同城活动下的地址
		.content_text_address {
      display: flex;
      align-items: center;
			max-width: 100%;
      white-space: nowrap;
      /* 防止文本换行 */
      overflow: hidden;
      /* 超出部分隐藏 */
      text-overflow: ellipsis;
      /* 显示省略号 */
      .content_text_location{

        font-size: 24rpx;
        text-align: left;
        color: #666666;
        max-width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        
      }
		}

    .content_text_actStatus{
      height: 32rpx;
      width: 72rpx;
      line-height: 32rpx;
      background-color: #f7f7f7;
      color: #666666;
      font-size: 20rpx;
      text-align: center;
    }
	}
}
.box_content :last-child{
  margin-bottom: 0px;
}


// 同城活动   右侧文字部分
.act_text{
  width: calc(80% - 20rpx);
  display: flex;
  justify-content: space-between;
  flex-direction: column;
}

.activity_content{
  margin-top: 30rpx;
}



.loading-text, .no-more-text {
    padding: 20rpx;
    text-align: center;
    color: #888;
    font-size: 24rpx;
}

.loading {
  text-align: center;
  /* height: 40px; */
  margin-top: 16px;
  color: #242629;
  // font-weight: 400;
  font-size: 14px;
}

::v-deep .van-nav-bar {
  // background-color: #f9f9f9 !important;
  z-index: 999 !important;
}

::v-deep .van-nav-bar__left {
  width: 56px;
  height: 44px;
}

::v-deep #navBar .van-icon {
  color: #242629 !important;
}


::v-deep .van-empty__image {
  width: 150px;
  height: 100px;

}

::v-deep .van-calendar__day--start {
  border-radius: 50% !important;
}
::v-deep .van-calendar__day--end{
  border-radius: 50% !important;
}

.pl15 {
  padding-left: 15px;
}

.pr15 {
  padding-right: 15px;
}
</style>